package com.lxk.service.event.handler;

import com.lxk.common.EventTypeEnum;
import com.lxk.common.GsonUtils;
import com.lxk.domain.dto.VisitorInfoDto;
import com.lxk.service.event.AbstractEventHandler;
import com.lxk.service.event.domain.EventDto;
import com.lxk.service.outer.GeoService;
import com.lxk.utils.TraceUtil;
import com.ning.http.client.AsyncHttpClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.Arrays;
import java.util.List;

@Slf4j
@Component
public class VisitEventHandler extends AbstractEventHandler<EventDto> {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    private GeoService geoService;

    @Override
    public List<EventTypeEnum> supports() {
        return Arrays.asList(EventTypeEnum.EVENT_VISITOR_COME);
    }

    @Override
    public boolean handleEvent(EventDto eventDto) {
        TraceUtil.genTrace("visit_info_event");
        log.info("发送客户来访信息 :: eventDto:{}",eventDto);
        VisitorInfoDto visitorInfoDto = GsonUtils.getGson().fromJson(eventDto.getContent(),VisitorInfoDto.class);
        GeoService.GeoResponse geoResponse = geoService.fromIp2Addr(visitorInfoDto.getVisitIp());
        log.info("根据ip查询物理地址 :: visitorInfoDto:{},geoResponse:{}",visitorInfoDto,geoResponse);
        if(!ObjectUtils.isEmpty(geoResponse)&&"1".equals(geoResponse.getStatus())&&"10000".equals(geoResponse.getInfocode())){
            visitorInfoDto.setProvince(geoResponse.getProvince());
            visitorInfoDto.setCity(geoResponse.getCity());
            visitorInfoDto.setAdCode(geoResponse.getAdcode());
            visitorInfoDto.setRectangle(geoResponse.getRectangle());
        }
        String visitorInfo = GsonUtils.getGson().toJson(visitorInfoDto);
        log.info("发送客户来访详细信息到mq :: visitorInfo:{}",visitorInfo);
        rabbitTemplate.convertAndSend("blog-exchange","blog",visitorInfo);
        TraceUtil.cleanTrace();
        return true;
    }

    @Override
    public boolean isFailedRetry() {
        return false;
    }

    @Override
    public Class<EventDto> eventType() {
        return EventDto.class;
    }
}
